package com.xiguanlezz.cn.codec.serialize;

import com.xiguanlezz.cn.codec.exception.SerializeException;

import java.io.*;
import java.util.Objects;

/**
 * @Author：习惯了种种
 * @CreateDate：2024/11/4 12:48
 * @Description：JDK序列化/反序列化器
 */
public class JdkSerializer implements Serialize {
    @Override
    public <T> byte[] serialize(T obj) {
        if (Objects.isNull(obj)) {
            throw new SerializeException("serialize obj is null...");
        }
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            return bos.toByteArray();
        } catch (IOException e) {
            throw new SerializeException(e.getMessage(), e);
        }
    }

    @Override
    public <T> T deserialize(byte[] bs, Class<T> clazz) {
        if (isEmpty(bs)) {
            throw new SerializeException("deserialize obj is null...");
        }
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bs);
            ObjectInputStream ois = new ObjectInputStream(bis);
            return (T) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new SerializeException(e.getMessage(), e);
        }
    }

    private static boolean isEmpty(byte[] bs) {
        return bs == null || bs.length == 0;
    }
}
